package online.heycm.rbac.domain.user.aggregate;

import lombok.Getter;
import online.heycm.rbac.common.entity.Session;
import online.heycm.rbac.domain.basic.repository.entity.BasicRbacRole;
import online.heycm.rbac.domain.user.repository.entity.UserAuthorize;
import online.heycm.rbac.domain.user.repository.entity.UserProfile;
import online.heycm.rbac.domain.user.repository.entity.UserRole;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 管理平台用户聚合根
 *
 * @author hey
 * @version 1.0
 * @date 2024/1/11 17:33
 */
@Getter
public class ConsoleUser {

    private final UserProfile userProfile;

    private final UserAuthorize userAuthorize;

    private Set<BasicRbacRole> roles;

    public ConsoleUser(UserProfile userProfile, UserAuthorize userAuthorize) {
        this.userProfile = userProfile;
        this.userAuthorize = userAuthorize;
    }

    public int getUserId() {
        return userProfile.getUserId();
    }

    public void addRole(BasicRbacRole role) {
        if (roles == null) {
            roles = new HashSet<>();
        }
        roles.add(role);
    }

    public Session createSession() {
        Session session = new Session();
        session.setUserId(userProfile.getUserId());
        session.setPhone(userProfile.getPhone());
        session.setUsername(userProfile.getUsername());
        session.setIdCard(userProfile.getIdCard());
        if (!CollectionUtils.isEmpty(roles)) {
            String[] roleCodes = new String[roles.size()];
            int[] roleIds = new int[roles.size()];
            int i = 0;
            for (BasicRbacRole role : roles) {
                roleCodes[i] = role.getRoleEn();
                roleIds[i] = role.getRoleId();
                i++;
            }
            session.setRoleCodes(roleCodes);
            session.setRoleIds(roleIds);
        }
        session.setLoginTime(new Date());
        return session;
    }

    public List<UserRole> createdUserRoles() {
        return createdUserRoles(false);
    }

    public List<UserRole> createdUserRoles(boolean needCreatedAt) {
        if (CollectionUtils.isEmpty(roles)) {
            return Collections.emptyList();
        }
        Date createdAt = needCreatedAt ? new Date() : null;
        return roles.stream().map(role -> {
            UserRole userRole = new UserRole();
            userRole.setRoleId(role.getRoleId());
            userRole.setUserId(userProfile.getUserId());
            userRole.setCreatedAt(createdAt);
            return userRole;
        }).collect(Collectors.toList());
    }

}
